# views/gallery.py

import os
import logging
from PyQt5.QtWidgets import (
    QWidget, QLabel, QPushButton, QHBoxLayout, QVBoxLayout, QFileDialog,
    QSlider, QGridLayout, QScrollArea
)
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt, QSize
from utils.image_utils import ImageUtils

class Gallery(QWidget):
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window

        # 初始化变量
        self.image_files = []
        self.thumbnail_size = 150  # 增大默认缩略图大小
        self.image_labels = {}  # 用于存储图像路径到 QLabel 的映射

        # 图像处理工具
        self.image_utils = ImageUtils(self.thumbnail_size)
        self.image_utils.thumbnail_ready.connect(self.on_thumbnail_ready)

        # 创建控件
        self.create_widgets()

    def create_widgets(self):
        layout = QVBoxLayout(self)

        # 缩略图大小调整滑块和放大缩小按钮
        top_layout = QHBoxLayout()
        size_label = QLabel("缩略图大小")
        top_layout.addWidget(size_label)

        self.thumbnail_size_slider = QSlider(Qt.Horizontal)
        self.thumbnail_size_slider.setMinimum(150)  # 增大最小值
        self.thumbnail_size_slider.setMaximum(600)  # 增大最大值
        self.thumbnail_size_slider.setValue(self.thumbnail_size)
        self.thumbnail_size_slider.valueChanged.connect(self.on_thumbnail_size_change)
        top_layout.addWidget(self.thumbnail_size_slider)

        # 放大缩小按钮
        zoom_in_button = QPushButton("放大")
        zoom_in_button.clicked.connect(self.zoom_in)
        top_layout.addWidget(zoom_in_button)

        zoom_out_button = QPushButton("缩小")
        zoom_out_button.clicked.connect(self.zoom_out)
        top_layout.addWidget(zoom_out_button)

        top_layout.addStretch()
        layout.addLayout(top_layout)

        # 滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_content = QWidget()
        self.grid_layout = QGridLayout(self.scroll_content)
        self.scroll_area.setWidget(self.scroll_content)

        layout.addWidget(self.scroll_area)

        # 显示占位符
        self.display_placeholder()

    def load_images(self):
        directory = self.main_window.directory
        if not os.path.isdir(directory):
            self.display_placeholder()
            logging.warning("图库加载失败：目录不存在。")
            return

        self.image_files = []
        for filename in os.listdir(directory):
            if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')):
                image_path = os.path.join(directory, filename)
                self.image_files.append(image_path)

        self.update_gallery()
        logging.info(f"图库加载完成，共 {len(self.image_files)} 张图片。")

    def update_gallery(self):
        # 清空原有内容
        for i in reversed(range(self.grid_layout.count())):
            widget_to_remove = self.grid_layout.itemAt(i).widget()
            self.grid_layout.removeWidget(widget_to_remove)
            widget_to_remove.setParent(None)
        self.image_labels.clear()

        if not self.image_files:
            self.display_placeholder()
            return

        thumbnails_per_row = self.calculate_thumbnails_per_row()
        for idx, image_path in enumerate(self.image_files):
            row = idx // thumbnails_per_row
            col = idx % thumbnails_per_row

            thumbnail_label = QLabel("加载中...")
            thumbnail_label.setFixedSize(self.thumbnail_size, self.thumbnail_size)
            thumbnail_label.setAlignment(Qt.AlignCenter)
            thumbnail_label.setStyleSheet("border: 1px solid gray;")
            thumbnail_label.setText("加载中...")

            # 绑定点击事件，确保每个 lambda 捕获当前的 image_path
            thumbnail_label.mousePressEvent = self.create_mouse_press_event(image_path)

            self.grid_layout.addWidget(thumbnail_label, row, col)

            # 存储映射
            self.image_labels[image_path] = thumbnail_label

            # 异步加载缩略图
            self.image_utils.generate_thumbnail(image_path)

    def create_mouse_press_event(self, image_path):
        def mouse_press_event(event):
            self.select_image_from_gallery(image_path)
        return mouse_press_event

    def calculate_thumbnails_per_row(self):
        gallery_width = self.scroll_area.width()
        thumbnails_per_row = max(1, gallery_width // (self.thumbnail_size + 20))
        return thumbnails_per_row

    def on_thumbnail_size_change(self, value):
        self.thumbnail_size = value
        self.image_utils.thumbnail_size = self.thumbnail_size
        self.image_utils.cache.clear()
        self.update_gallery()
        logging.info(f"图库缩略图大小调整为：{self.thumbnail_size}")

    def zoom_in(self):
        self.thumbnail_size += 10
        if self.thumbnail_size > 600:
            self.thumbnail_size = 600
        self.thumbnail_size_slider.setValue(self.thumbnail_size)
        self.main_window.viewer.thumbnail_size = self.thumbnail_size
        logging.info(f"图库缩放放大，当前缩略图大小：{self.thumbnail_size}")

    def zoom_out(self):
        self.thumbnail_size -= 10
        if self.thumbnail_size < 150:
            self.thumbnail_size = 150
        self.thumbnail_size_slider.setValue(self.thumbnail_size)
        self.main_window.viewer.thumbnail_size = self.thumbnail_size
        logging.info(f"图库缩放缩小，当前缩略图大小：{self.thumbnail_size}")

    def on_thumbnail_ready(self, image_path, pixmap):
        # 根据图像路径找到对应的 QLabel 并设置缩略图
        if image_path in self.image_labels:
            label = self.image_labels[image_path]
            label.setPixmap(pixmap.scaled(
                self.thumbnail_size, self.thumbnail_size, Qt.KeepAspectRatio, Qt.SmoothTransformation))
            label.setText("")  # 清除加载中...
            logging.info(f"图库缩略图已加载：{image_path}")

    def select_image_from_gallery(self, image_path):
        if image_path in self.image_files:
            self.main_window.viewer.current_index = self.image_files.index(image_path)
            self.main_window.viewer.update_image()
            self.main_window.tab_widget.setCurrentWidget(self.main_window.viewer)
            logging.info(f"从图库选择并显示图片：{image_path}")

    def display_placeholder(self):
        # 清空原有内容
        for i in reversed(range(self.grid_layout.count())):
            widget_to_remove = self.grid_layout.itemAt(i).widget()
            self.grid_layout.removeWidget(widget_to_remove)
            widget_to_remove.setParent(None)
        placeholder_label = QLabel("请在图片查看窗口中打开或拖入图片文件夹")
        placeholder_label.setAlignment(Qt.AlignCenter)
        self.grid_layout.addWidget(placeholder_label, 0, 0)
        logging.info("图库显示占位符：请在图片查看窗口中打开或拖入图片文件夹。")

    def resizeEvent(self, event):
        self.update_gallery()
        super().resizeEvent(event)
